package com.qyb.zx;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 实现功能：
 * <p/>
 *
 * @author 秦有宝
 * @version 1.0.00
 */
public class EinvoiceRecognizeUtil {

    public static String recogonize(InputStream input) throws IOException{
        PDDocument doc = PDDocument.load(input);
        String reimEinvoiceItem = doRecogonize(doc, 200);
        if(Objects.isNull(reimEinvoiceItem)){
            reimEinvoiceItem = doRecogonize(doc, 2*72);
        }
        return reimEinvoiceItem;
    }

    public static String doRecogonize(PDDocument doc, float dpi) throws IOException{
        int MAX_PIXELS = 1 << 25;
        BufferedImage bufferedImage = null;
        PDFRenderer renderer = new PDFRenderer(doc);
        bufferedImage = renderer.renderImageWithDPI(0, dpi, ImageType.GRAY);

        if (bufferedImage == null) {
            return null;
        }
        try {
            ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\qqqq.png"));
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if (height <= 1 || width <= 1 || height * width > MAX_PIXELS) {
                return null;
            }
            return processImage(bufferedImage);
        } finally {
            bufferedImage.flush();
        }
    }

    private static String processImage(BufferedImage image)  {
        Map<DecodeHintType,Object> HINTS = new EnumMap<>(DecodeHintType.class);
        HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        HINTS.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
        Map<DecodeHintType,Object> HINTS_PURE = new EnumMap<>(HINTS);
        HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);

        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
        List<Result> results = new ArrayList<>(1);
        try {
            Reader reader = new MultiFormatReader();
            ReaderException savedException = null;
            if (results.isEmpty()) {
                try {
                    // Look for normal barcode in photo
                    Result theResult = reader.decode(bitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()) {
                try {
                    // Try again with other binarizer
                    BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result theResult = reader.decode(hybridBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()) {
                try {
                    // Look for multiple barcodes
                    MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
                    Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
                    if (theResults != null) {
                        results.addAll(Arrays.asList(theResults));
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()) {
                try {
                    // Look for pure barcode
                    Result theResult = reader.decode(bitmap, HINTS_PURE);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()) {
                try {
                    throw savedException == null ? NotFoundException.getNotFoundInstance() : savedException;
                } catch (FormatException | ChecksumException e) {

                } catch (ReaderException e) {

                }
            }

        } catch (RuntimeException re) {
        }
        if (results.isEmpty()) {
            return null;
        }
        String qrCodeStrs = results.get(0).getText();
        return qrCodeStrs;

    }

    @Deprecated
    public static String recogonizeOld(InputStream input) throws IOException{
        BufferedImage bufferedImage = null;
        PDDocument doc = PDDocument.load(input);
        PDFRenderer renderer = new PDFRenderer(doc);
        int pageCount = doc.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) {
            // 方式1,第二个参数是设置缩放比(即像素)
            //bufferedImage = renderer.renderImageWithDPI(i, 296);
            // 方式2,第二个参数是设置缩放比(即像素)
            bufferedImage = renderer.renderImage(i, 300 / 72f);
//                ImageIO.write(bufferedImage, "PNG", new File("D:\\tt\\111.png"));
        }

        // BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        //乱码。解码设置编码方式为：utf-8，
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        //优化精度
        decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        //开启PURE_BARCODE模式。（这是解决我的方案，带图片LOGO的解码方案）
        //复杂模式，开启PURE_BARCODE模式
        //decodeHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, decodeHints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String qrCode = result.getText();
        if(qrCode==null){
            return null;
        }else{
            String[] qrCodeStrs = qrCode.split(",");

            return qrCode;
        }
    }
}
